package logic

import (
	"context"
	"net/http"
	"path/filepath"
	"shuqi-novel/pkg"

	"shuqi-novel/api/internal/svc"
	"shuqi-novel/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type FileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileLogic {
	return &FileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FileLogic) File(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	file, m, err := req.FormFile("file")
	if err != nil {
		return &types.Response{
			Message: "文件上传失败",
			Data:    nil,
			Code:    500,
		}, nil
	}
	ext := filepath.Ext(m.Filename)
	if ext != ".png" && ext != ".jpg" {
		return &types.Response{
			Message: "文件类型不正确",
			Data:    nil,
			Code:    500,
		}, nil
	}
	if m.Size > 2*1024*1024 {
		return &types.Response{
			Message: "文件大小不正确",
			Data:    nil,
			Code:    500,
		}, nil
	}
	files, err := pkg.File(file, m)
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Data:    nil,
			Code:    500,
		}, nil
	}
	return &types.Response{
		Message: "文件上传成功",
		Data:    files,
		Code:    200,
	}, nil
}
